$(function () {
    /**
     * 分页初始条件
     */
    var total_count = 1;//分页总记录数
    var total = 1;//分页总页面数
    var currentPage = 1;//当前页
    var pageSize = pageOption.pageSize;//每页显示的记录数
    var idList = [];//批量选择id所存的数组
    var root_url = $("#root_url").val();

    /**
     * 页面初始化
     */
    function init() {
        myPagination();
        bindEvent();
    }

    /**
     * 事件绑定
     */
    function bindEvent() {
        $(".right-section ul.nav.tab-list li a").click(function(){
            var href = $(this).attr("href");
            location.href=href;
        });

        //根据条件查询订单信息
        $('.inner-section #search_btn').click(function () {
            render(true, 1, pageSize);
            return false;
        });

        //enter键盘事件
        $(".inner-section .search-param-form input").keydown(function (event) {
            event = event ? event : window.event;
            if (event.keyCode == 13) {
                render(true, 1, pageSize);
                return false;
            }
        });

        //导出
        $('.row #import_btn').click(function () {
            var selectInfo = getSelectInfo();
            var data = $.param(selectInfo);
            window.location.href = "importExcel?" + data;
        });
    }

    /**
     * 获取模糊参数
     */
    function getSelectInfo() {
        var selectInfo = {};
        $.each($('#search-param-form').serializeArray(), function (i, field) {
            selectInfo[field.name] = field.value;
        });
        JSON.stringify(selectInfo);
        return selectInfo;
    }

    /**
     * 分页显示方法
     */
    function myPagination() {
        render(true, 1, pageSize);
        //调用公共分页方法
        pagination("#page-selection", {pageSize: pageSize, total: total}, render);
    }

    /**
     * 分页动态渲染数据
     * @param async ajax请求是否异步
     * @param pageIndex 当前显示页
     * @param pageSize 每页显示记录数
     */
    function render(async, pageIndex, pageSize) {
        var selectInfo = getSelectInfo();
        selectInfo.pageIndex = pageIndex;
        selectInfo.pageSize = pageSize;
        $.ajax({
            async: async,
            type: 'post',
            url: 'pagingStore',
            data: selectInfo,//从1开始计数
            dataType: 'json',
            success: function (result) {
                var html = '';
                if (result.errorCode == 0) {
                    total = result.data.pageInfo.total_page;
                    total_count = result.data.pageInfo.total_count;
                    $("#page-selection").bootpag({total: total, total_count: total_count});//重新计算总页数,总记录数

                    currentPage = result.data.pageInfo.current_page;
                    var myList = result.data.dataList;

                    html += '<tr>' +
                        '<th class="th1">序号</th>' +
                        '<th class="">账号</th>' +
                        '<th class="">密码</th>' +
                        '<th class="">门店名称</th>' +
                        '<th class="">所在城市</th>' +
                        '<th class="">详细地址</th>' +
                        '<th class="">添加时间</th>' +
                        '<th class="">状态</th>' +
                        '<th class="">绑定用户</th>' +
                        '<th class="">绑定时间</th>' +
                        '<th class="" style="width: 140px;">上级用户</th>' +
                        '<th class="" style="width: 140px;">操作</th>' +
                        '</tr>';
                    var colspan = $(html).find("th").length;
                    for (var i = 0; i < myList.length; i++) {
                        var obj = myList[i];
                        var num = (pageIndex - 1) * pageSize + i + 1;
                        var user_id = obj.user_id;
                        var username = obj.username;
                        var password = obj.password;
                        var memberUsername = obj.memberUsername || '';
                        var title = obj.title;
                        var city = obj.city;
                        var address = obj.address;
                        var add_time = obj.add_time;
                        var bind_time = obj.bind_time;
                        var state = obj.state;
                        var parent_nick_name = obj.parent_nick_name;
                        var id = obj.id;

                        var checked = (idList.indexOf(id) >= 0) ? "checked" : "";//判断当前记录先前有没有被选中
                        if (add_time == null) add_time = '--'
                        if (bind_time == null) bind_time = '--'

                        var audit_html = '';
                        if (state == 1) {
                            audit_html = '<a href="javascript:;" data-id="' + id + '" data-status="0" class="auditStatus" style="color: green">开启</a>';
                        } else {
                            audit_html = '<a href="javascript:;" data-id="' + id + '" data-status="1" class="auditStatus" style="color: red">禁用</a>';
                        }

                        var state_text = '开启'
                        if (state == 1) state_text = '禁用'

                        var memberUsernameText = '';
                        if (memberUsername == '') {
                            memberUsernameText += '<span class="username"></span> <span data-id="'+id+'" class="replaceUser" style="cursor: pointer;color: green;">添加</span>';
                        } else {
                            memberUsernameText = '<span class="username">'+parent_nick_name+'</span> <span data-id="'+id+'" class="replaceUser" style="cursor: pointer;color: green;">替换</span>';
                        }

                        html += '<tr>'
                            + '<td class="">' + num + '</td>'
                            + '<td class="">' + username + '</td>'
                            + '<td class="">' + password + '</td>'
                            + '<td class="">' + title + '</td>'
                            + '<td class="">' + city + '</td>'
                            + '<td class="">' + address + '</td>'
                            + '<td class="">' + add_time + '</td>'
                            + '<td class="">' + state_text + '</td>'
                            + '<td class="">' + memberUsername + '</td>'
                            + '<td class="">' + bind_time + '</td>'
                            + '<td class="">' + memberUsernameText + '</td>'
                            + '<td>'
                            + '<div>'
                            + audit_html
                            + '<a href="editStore?id=' + id + '" data-id="' + id + '" class="edit-order">编辑</a>'
                            + '<a href="javascript:;" data-id="' + id + '" class="delete-store">删除</a>'
                            + '</div>'
                            + '<div style="margin-top: 5px">'
                            + '<a href="javascript:;" data-id="' + id + '" class="change-password">重置密码</a>'
                            + '<a href="../BalanceRecords/balance5List?mid=132&id=' + id + '" data-id="' + id + '" class="edit-order">收益明细</a>'
                            + '</div>'
                            + '</td>'
                            + '</tr>';
                    }

                    if (myList.length == 0) {
                        html += '<tr><td colspan="' + colspan + '"><p class="text-danger">暂无数据。</p></td></tr>';
                        $("#list-table tbody").html(html);
                    } else {
                        $("#list-table tbody").html(html);
                        myCheck();
                        batchSelect(idList, ".inner-section #list-table .select-all", ".inner-section #list-table .select-single");

                        //删除
                        $("#list-table .delete-store").click(deleteStore);
                        //重置密码
                        $("#list-table .change-password").click(changePassword)
                        //替换
                        $("#list-table .replaceUser").click(assignUser)
                        //替换
                        $("#list-table .auditStatus").click(disabledStatus)
                    }
                } else {
                    responseTip(result.errorCode, result.errorInfo, 1500);
                }
            },
            error: errorResponse
        });
    }

    function assignUser() {
        var that = $(this)
        var id = that.attr('data-id');
        layer.open({
            type: 2,
            title: '绑定用户',
            shadeClose: true,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['80%', '700px'],
            content: "../User/bindUser",
            btn: ['确定', '关闭'],
            yes: function (index) {
                //当点击‘确定'按钮的时候，获取弹出层返回的值
                var customer_info = window["layui-layer-iframe" + index].getData();
                console.log(customer_info)
                if (customer_info.user == '-1') {
                    return layer.alert('请选择用户');
                }
                // $('input[name="user_id"]').val(customer_info.user.id)
                // $('.showUserInfo').html('已选中的用户：'+customer_info.user.nick_name)
                //最后关闭弹出层
                layer.close(index);
                setStoreUser(customer_info.user.id,id,that)
            }
        });
    }

    function setStoreUser (user_id,store_id,obj)
    {
        $.ajax({
            url: "setStoreUser",
            type: "post",
            data: {"user_id": user_id,"store_id":store_id},
            dataType: "json",
            beforeSend: function (xhr) {
                //显示“加载中。。。”
                $("#loading").modal('show');
            },
            complete: function () {
                //隐藏“加载中。。。”
                $("#loading").modal('hide');
            },
            success: function (json, statusText) {
                if (json.errorCode == 1) {
                    return layer.msg(json.errorInfo);
                }
                obj.siblings('span.username').html(json.data.username)
            },
            error: errorResponse
        });
    }

    function changePassword ()
    {
        var id = $(this).attr('data-id');
        layer.prompt({title: '请重置密码', formType: 1}, function(pass, index){
            layer.close(index);
            $.ajax({
                url: "changePassword",
                type: "post",
                data: {"id": id,"pass":pass},
                dataType: "json",
                beforeSend: function (xhr) {
                    //显示“加载中。。。”
                    $("#loading").modal('show');
                },
                complete: function () {
                    //隐藏“加载中。。。”
                    $("#loading").modal('hide');
                },
                success: function (json, statusText) {
                    if (json.errorCode == 0) {
                        layer.msg(json.errorInfo)
                        if (currentPage != 1 && total_count % pageSize == 1) {//非首页且末页记录数为1时
                            currentPage = currentPage - 1;
                        }
                        render(true, currentPage, pageSize);
                    } else {
                        responseTip(json.errorCode, json.errorInfo, 1500);
                    }
                },
                error: errorResponse
            });
        });
    }

    // 删除
    function deleteStore() {
        var id = $(this).attr("data-id");
        myConfirmModal("确定删除吗？", function () {
            $.ajax({
                url: "deleteStore",
                type: "post",
                data: {"id": id},
                dataType: "json",
                beforeSend: function (xhr) {
                    //显示“加载中。。。”
                    $("#loading").modal('show');
                },
                complete: function () {
                    //隐藏“加载中。。。”
                    $("#loading").modal('hide');
                },
                success: function (json, statusText) {
                    if (json.errorCode == 0) {
                        if (currentPage != 1 && total_count % pageSize == 1) {//非首页且末页记录数为1时
                            currentPage = currentPage - 1;
                        }
                        render(true, currentPage, pageSize);
                    } else {
                        responseTip(json.errorCode, json.errorInfo, 1500);
                    }
                },
                error: errorResponse
            });
        });
    }

    // 开关
    function disabledStatus() {
        var id = $(this).attr('data-id');
        var status = $(this).attr('data-status');
        myConfirmModal("确定执行此操作吗？", function () {
            $.ajax(
                {
                    type: "post",
                    url: "disabledStatus",
                    data: {"id": id, "state": status},
                    dataType: "json",
                    beforeSend: function (xhr) {
                        //显示“加载中。。。”
                        $("#loading").modal('show');
                    },
                    complete: function () {
                        //隐藏“加载中。。。”
                        $("#loading").modal('hide');
                    },
                    success: function (json, statusText) {
                        if (json.errorCode == 0) {
                            if (currentPage != 1 && total_count % pageSize == 1) {//非首页且末页记录数为1时
                                currentPage = currentPage - 1;
                            }
                            render(true, currentPage, pageSize);
                        } else {
                            responseTip(json.errorCode, json.errorInfo, 1500);
                        }
                    },
                    error: errorResponse
                }
            );
        });
    }

    init();
});